package com.book.lizhi.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.internal.view.menu.MenuBuilder;
import android.support.v7.widget.ListPopupWindow;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.book.lizhi.AppApplication;
import com.book.lizhi.BaseActivity;
import com.book.lizhi.R;
import com.book.lizhi.adapter.BookshelfAdaper;
import com.book.lizhi.adapter.MorePopupAdapter;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.database.DataBaseMannager;
import com.book.lizhi.model.BookshelfModel;
import com.book.lizhi.model.EmptyBookModel;
import com.book.lizhi.read.ReadActivity;
import com.book.lizhi.util.FileUtil;

public class BookshelfActivity extends BaseActivity {
	private GridView mGridView;
	private BookshelfAdaper mAdaper;

	private View mMenuView;
	private TextView mCanceView;
	private TextView mDeteleView;

	private View mDeletePanel;
	private View mDeleteCancelView;
	private View mDeleteOkView;
	private CheckBox mDeleteCheckBox;

	private ListPopupWindow mMorePopupWindow;

	private int mCheckCount = 0;

	private BroadcastReceiver checkReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			boolean isCheck = intent.getBooleanExtra(Constants.IS_CHECK, true);
			if (isCheck) {
				mCheckCount++;
			} else {
				mCheckCount--;
			}

			if (mCheckCount == 0) {
				mDeteleView.setBackgroundResource(R.drawable.bookshelf_btn_cancel_backgroud);
			} else {
				mDeteleView.setBackgroundResource(R.drawable.bookshelf_btn_cancel_backgroud_selector);
			}
			mDeteleView.setText("删除所选(" + mCheckCount + ")");
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bookshelf);

		initUI();

		LocalBroadcastManager.getInstance(this).registerReceiver(checkReceiver, new IntentFilter(Constants.BOOKSHELF_CHECK_ACTION));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.bookshelf, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_book_library) {
			startActivity(new Intent(getApplicationContext(), LibraryActivity.class));
			return true;
		} else if (id == R.id.action_more) {
			showMorePopupWindow(findViewById(id));
		}
		return super.onOptionsItemSelected(item);
	}

	private void showMorePopupWindow(View view) {

		mMorePopupWindow = new ListPopupWindow(this);
		MenuBuilder menu = new MenuBuilder(this);
		getMenuInflater().inflate(R.menu.more_bookshlef, menu);
		MorePopupAdapter adapter = new MorePopupAdapter(this, menu);
		mMorePopupWindow.setWidth(adapter.getWidth());
		mMorePopupWindow.setAdapter(adapter);
		mMorePopupWindow.setModal(true);
		mMorePopupWindow.setAnchorView(view);
		mMorePopupWindow.setOnItemClickListener(moreMenuListener);
		mMorePopupWindow.show();

	}

	private void initUI() {

		ActionBar actionBar = getSupportActionBar();
		actionBar.setTitle("我的书架");
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setHomeButtonEnabled(false);

		mGridView = (GridView) findViewById(R.id.bookshelf_gridview);
		mAdaper = new BookshelfAdaper(this, AppApplication.instance.bookshelfModels);
		mGridView.setAdapter(mAdaper);

		// 书架管理菜单
		mMenuView = findViewById(R.id.bookshelf_check_menu);
		mMenuView.setVisibility(View.GONE);
		mCanceView = (TextView) findViewById(R.id.menu_cancel_view);
		mDeteleView = (TextView) findViewById(R.id.menu_delete_view);

		// 确认删除
		mDeletePanel = findViewById(R.id.delete_panel_view);
		mDeleteCancelView = findViewById(R.id.delete_cancel_view);
		mDeleteOkView = findViewById(R.id.delete_ok_view);
		mDeleteCheckBox = (CheckBox) findViewById(R.id.delete_checkBox);

		addOnListenner();
	}

	@Override
	protected void onResume() {
		super.onResume();
		AppApplication.instance.bookshelfModels.clear();
		AppApplication.instance.bookshelfIDs.clear();
		AppApplication.instance.bookshelfModels.addAll(0, loadDataFromLocal());
		AppApplication.instance.bookshelfModels.add(new EmptyBookModel());
		for (BookshelfModel model : AppApplication.instance.bookshelfModels) {
			AppApplication.instance.bookshelfIDs.add(model.id);
		}
		mAdaper.notifyDataSetChanged();
	}

	private List<BookshelfModel> loadDataFromLocal() {
		return DataBaseMannager.getInstance().queryBookshelfs(this);
	}

	private OnItemClickListener moreMenuListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			mMorePopupWindow.dismiss();
			 if (id == R.id.action_manage_book) {
				mMenuView.setVisibility(View.VISIBLE);
				for (BookshelfModel bookshelfModel : AppApplication.instance.bookshelfModels) {
					bookshelfModel.isCheckModel = true;
					bookshelfModel.isCheck = false;
				}
				mAdaper.notifyDataSetChanged();
			} else if (id == R.id.action_setting) {
				startActivity(new Intent(getApplicationContext(), UserInfoActivity.class));
			}
		}
	};

	private void addOnListenner() {

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object object = mAdaper.getItem(position);
				if (object instanceof EmptyBookModel) {
					startActivity(new Intent(getApplicationContext(), LibraryActivity.class));
				} else {
					BookshelfModel model = (BookshelfModel) object;
					AppApplication.instance.currentBookModel = model;
					Intent intent = new Intent(getApplicationContext(), ReadActivity.class);
					startActivity(intent);
				}
			}

		});
		mCanceView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mMenuView.setVisibility(View.GONE);
				for (BookshelfModel model : AppApplication.instance.bookshelfModels) {
					model.isCheck = false;
					model.isCheckModel = false;
				}
				mAdaper.notifyDataSetChanged();
				resetDeleteView();
			}
		});
		mDeteleView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mCheckCount <= 0) {
					return;
				}
				mDeletePanel.setVisibility(View.VISIBLE);

			}
		});

		mDeleteCancelView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				cancelControllBook();
			}
		});
		mDeleteOkView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				List<BookshelfModel> bookshelfModels = new ArrayList<BookshelfModel>();
				for (BookshelfModel model : AppApplication.instance.bookshelfModels) {
					model.isCheckModel = false;
					if (model.isCheck) {
						DataBaseMannager.getInstance().deleteValueById(getApplicationContext(), model.id);
						bookshelfModels.add(model);
						if (mDeleteCheckBox.isChecked()) {
							FileUtil.deleteFile(new File(FileUtil.getCacheFile(), model.id));
						}
					}
				}
				AppApplication.instance.bookshelfModels.removeAll(bookshelfModels);
				mAdaper.notifyDataSetChanged();
				mDeletePanel.setVisibility(View.GONE);
				mMenuView.setVisibility(View.GONE);
				resetDeleteView();
			}
		});
	}

	protected void cancelControllBook() {
		for (BookshelfModel model : AppApplication.instance.bookshelfModels) {
			model.isCheck = false;
			model.isCheckModel = false;
		}
		mAdaper.notifyDataSetChanged();
		mDeletePanel.setVisibility(View.GONE);
		mMenuView.setVisibility(View.GONE);
		resetDeleteView();
	}

	protected void resetDeleteView() {
		mCheckCount = 0;
		mDeteleView.setBackgroundResource(R.drawable.bookshelf_btn_cancel_backgroud);
		mDeteleView.setText("删除所选(" + mCheckCount + ")");
	}

	int backCounter = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mMenuView.getVisibility() == View.VISIBLE) {
				cancelControllBook();
				return true;
			}
			backCounter++;
			new Thread(new Runnable() {
				public void run() {
					try {
						Thread.sleep(1000);
						backCounter++;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();

			if (backCounter >= 2) {
				finish();
			} else {
				Toast.makeText(getApplicationContext(), "再按一次就退出了!", Toast.LENGTH_SHORT).show();
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			showMorePopupWindow(findViewById(R.id.action_more));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(checkReceiver);
	}
}
